import React from 'react';
import { Link } from 'react-router-dom';
import { toJS } from 'mobx';
import { observer } from 'mobx-react';
import { Breadcrumb, Table, Pagination } from '@casstime/bricks';

import Page from '../../../components/Page';
import { parseLocationSearch, createLocationSearch } from '../../../utils';
import HomePageStore from '../stores/HomePageStore';
import { RouteConfigComponentProps } from 'react-router-config';

interface IHomePageProps extends RouteConfigComponentProps<void> {
  homePageStore: HomePageStore;
}

@observer
class Main extends React.Component<IHomePageProps, {}> {
  constructor(props: IHomePageProps) {
    super(props);
    this.toPage = this.toPage.bind(this);
  }

  toPage(page: number) {
    const search = createLocationSearch({ page });
    this.props.history.push({
      pathname: '/',
      search
    });
  }

  render() {
    const { homePageStore } = this.props;
    const query = parseLocationSearch(this.props.location.search);
    const page = parseInt(query.page as string, 10) || 1; // 确定包含page
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        align: 'center'
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        align: 'center'
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
        align: 'center'
      },
      {
        title: 'Operations',
        dataIndex: '',
        key: 'operations',
        align: 'center',
        render: (text: string, row: any, index: number) => {
          return (
            <div>
              <a
                onClick={homePageStore.removeListItem.bind(
                  homePageStore,
                  index
                )}
                href="#"
              >
                删除
              </a>
              <span style={{ margin: '0 4px' }}>|</span>
              <a
                onClick={homePageStore.changeName.bind(homePageStore, index)}
                href="#"
              >
                改名
              </a>
            </div>
          );
        }
      }
    ];

    const data = toJS(homePageStore.list);

    return (
      <Page title="主页">
        <Breadcrumb description="您当前的位置：">
          <Breadcrumb.Item active>
            <Link to="/">主页</Link>
          </Breadcrumb.Item>
        </Breadcrumb>
        <Table columns={columns} data={data} />
        <Pagination
          current={page}
          onChange={this.toPage}
          total={100}
          pageSize={10}
          showQuickJumper
        />
      </Page>
    );
  }
}

export default Main;
